<template>
  <div class='container'>
    <el-card class="box-card">
      <template v-slot:header>
        <span>试题{{ isEdit ? '修改' : '录入' }}</span>
      </template>
      <div>
        <!--        <el-form :model="uploadParams" :rules="rules" ref="uploadParams" label-width="100px" class="demo-ruleForm">-->
        <el-form :model="uploadParams" :rules="rules" ref="uploadParams" label-width="100px" class="demo-ruleForm">
          <!--    学科    -->
          <el-form-item
            label="学科:"
            prop="subjectID">
            <el-select v-model="uploadParams.subjectID" placeholder="请选择学科" style="width: 400px;"
                       @change="onSubjectChange">
              <el-option :key="item.value" v-for="item in subjectList" :label="item.label" :value="item.value"/>
            </el-select>
          </el-form-item>
          <!--    目录      -->
          <el-form-item
            label="目录:"
            prop="catalogID">
            <el-select v-model="uploadParams.catalogID" placeholder="请选择目录" style="width: 400px;">
              <el-option :key="item.value" v-for="item in catalogList" :label="item.label" :value="item.value"/>
            </el-select>
          </el-form-item>
          <!--    企业      -->
          <el-form-item
            label="企业:"
            prop="enterpriseID">
            <el-select v-model="uploadParams.enterpriseID" placeholder="请选择试题标签" style="width: 400px;">
              <el-option :key="item.value" v-for="item in companyList" :label="item.company" :value="item.id"/>
            </el-select>
          </el-form-item>
          <!--    城市      -->
          <el-form-item
            label="城市:"
            prop="city">
            <el-select v-model="uploadParams.province" placeholder="请选择城市" @change="onProvinceChang"
                       style="width: 198px;">
              <el-option :key="index" v-for="(item,index) in provinces" :label="item" :value="item"/>
            </el-select>
            <el-select v-model="uploadParams.city" placeholder="请选择区域" style="margin-left:4px;width: 198px">
              <el-option :key="index" v-for="(item,index) in citys" :label="item" :value="item"/>
            </el-select>
          </el-form-item>
          <!--    方向     -->
          <el-form-item
            label="方向:"
            prop="direction">
            <el-select v-model="uploadParams.direction" placeholder="请选择方向" style="width: 400px;">
              <el-option :key="item.value" v-for="item in directionList" :label="item" :value="item"/>
            </el-select>
          </el-form-item>
          <!--    题型  -->
          <el-form-item
            label="题型:"
            prop="questionType">
            <el-radio-group
              v-model="uploadParams.questionType"
              @change="onQuestionTypeChange">
              <el-radio
                :key="item.value"
                v-for="item in questionTypeList"
                :label="item.value.toString()">
                {{ item.label }}
              </el-radio>
            </el-radio-group>
          </el-form-item>
          <!--     难度  -->
          <el-form-item
            label="难度:"
            prop="difficulty">
            <el-radio-group v-model="uploadParams.difficulty">
              <el-radio
                :key="item.value"
                v-for="item in difficList"
                :label="item.value.toString()">
                {{ item.label }}
              </el-radio>
            </el-radio-group>
          </el-form-item>
          <!--     题干     -->
          <el-form-item
            label="题干:"
            prop="question"
          >
            <quillEditor class='rich-text' :options='editorOption' v-model="uploadParams.question"/>
          </el-form-item>
          <!--     选择题补充     -->
          <el-form-item
            label="选项:"
            prop="options"
            v-show="showOptionView">
            <el-radio-group
              v-model="mySelect"
              style="width: 400px;">
              <questions-select
                :key="index"
                v-for="(item,index) in uploadParams.options"
                :select-type="uploadParams.questionType"
                :index="index"
                v-model="uploadParams.options[index]"
                :select="mySelect"
                @onSingleSelect="mySelect=$event"/>
              <el-button :disabled="isSingleOption" type="danger" @click.prevent="addOption">+增加选项于答案</el-button>
            </el-radio-group>
          </el-form-item>
          <!--     解析视频    -->
          <el-form-item
            label="解析视频:"
            prop="videoURL">
            <el-input v-model="uploadParams.videoURL" style="width: 400px;"/>
          </el-form-item>

          <!--     答案解析    -->
          <el-form-item
            label="答案解析:"
            prop="answer">
            <quillEditor class='rich-text' :options='editorOption' v-model="uploadParams.answer"/>
          </el-form-item>

          <!--    题目备注      -->
          <el-form-item
            label="题目备注:"
            prop="remarks">
            <el-input
              type="textarea"
              :rows="4"
              v-model="uploadParams.remarks"
              style="width: 360px;">
            </el-input>
          </el-form-item>

          <!--     试题标签     -->
          <el-form-item
            label="试题标签:"
            prop="tags">
            <el-select
              multiple
              v-model="tagData"
              placeholder="请选择试题标签"
              style="width: 400px;">
              <el-option :key="item.value" v-for="item in tagList" :label="item.label" :value="item.label"/>
            </el-select>
          </el-form-item>
          <!--      提交按钮      -->
          <el-form-item>
            <el-button type="primary" @click.prevent="submitData">提交</el-button>
          </el-form-item>
        </el-form>
      </div>
    </el-card>
  </div>
</template>

<script>
import { provinces, citys } from '@/api/hmmm/citys'
import { simple } from '@/api/hmmm/subjects'
import { simple as simpleTag } from '@/api/hmmm/tags'
import { simple as sDirectorys } from '@/api/hmmm/directorys'
import { list as companyList } from '@/api/hmmm/companys'
import {
  add as addQuestions,
  detail as questionDetail,
  update as questionUpdate
} from '@/api/hmmm/questions'
import {
  direction as localDirection,
  difficulty as difficList,
  questionType as questionList
} from '@/api/hmmm/constants'

// require styles 引入样式
import 'quill/dist/quill.core.css'
import 'quill/dist/quill.snow.css'
import 'quill/dist/quill.bubble.css'
import { quillEditor } from 'vue-quill-editor'
import questionsSelect from '@/module-hmmm/components/questions-select'

export default {
  name: 'questions-new',
  components: {
    quillEditor,
    questionsSelect
  },
  data () {
    return {
      // 富文本配置
      editorOption: {
        placeholder: '',
        modules: {
          toolbar: [
            ['bold', 'italic', 'underline', 'strike'],
            ['blockquote', 'code-block'],
            [{ header: 1 }, { header: 2 }],
            [{ list: 'ordered' }, { list: 'bullet' }],
            [{ indent: '-1' }, { indent: '+1' }],
            ['image']
          ]
        }
      },
      // ------------------------ 展示数据 --------------------
      // 学科数据
      subjectList: [],
      // 学科细分类别
      catalogList: [],
      // 公司列表
      companyList: [],
      // 标签列表
      tagList: [],
      // 方向列表
      directionList: localDirection,
      mySelect: '',
      // ------------------------ 展示数据 --------------------
      // ------------------------ 表单提交数据 --------------------
      defaultUploadParams: {},
      uploadParams: {
        subjectID: null,
        catalogID: null,
        enterpriseID: null,
        province: null,
        city: null,
        direction: null,
        questionType: '1',
        difficulty: '1',
        question: null,
        options: new Array(4),
        tags: '',
        videoURL: null,
        answer: null,
        remarks: null
      },
      // ------------------------ 表单验证 --------------------
      rules: {
        subjectID: [{ required: true, message: '学科不能为空', trigger: 'blur' }],
        catalogID: [{ required: true, message: '目录不能为空' }],
        enterpriseID: [{ required: true, message: '企业不能为空', trigger: 'blur' }],
        province: null,
        city: [{ required: true, message: '城市不能为空' }],
        direction: [{ required: true, message: '方向不能为空', trigger: 'blur' }],
        question: [{ required: true, message: '题干不能为空', trigger: 'blur' }],
        answer: [{ required: true, message: '答案解析不能为空' }]
      }
      // ------------------------ 表单验证 --------------------
    }
  },
  methods: {
    clearFrom () {
      // 数据恢复关键代码
      this.uploadParams = this.$options.data().uploadParams
      this.mySelect = this.$options.data().mySelect
      this.$nextTick(() => {
        this.$refs.uploadParams.clearValidate()
      })
    },
    // http://hmmm-api.itheima.net/companys?pagesize=10000
    async getCompanys () {
      try {
        const res = await companyList()
        this.companyList = res.data.items
      } catch (e) {
      }
    },
    async getSimpleSubjects () {
      try {
        const res = await simple()
        this.subjectList = res.data
      } catch (e) {
      }
    },
    // 获取
    async getSimpleTag (sId) {
      try {
        const res = await simpleTag({
          subjectID: sId
        })
        this.tagList = res.data
      } catch (e) {
      }
    },
    // 获取学科方向细分信息
    async getSimpleDirectorys (sId) {
      try {
        const res = await sDirectorys({
          subjectID: sId
        })
        this.catalogList = res.data
      } catch (e) {
      }
    },
    // 提交数据
    async addQuestions () {
      try {
        await addQuestions(this.uploadParams)
        this.$message.success('提交成功')
        await this.$router.push('/questions/list')
      } catch (e) {
        console.log(e)
      }
    },
    // 修改数据
    async questionUpdate () {
      try {
        await questionUpdate(this.uploadParams)
        this.$message.success('提交成功')
        await this.$router.push('/questions/list')
      } catch (e) {
        console.log(e)
      }
    },
    // 获取数据
    async getQuestionsInfo (id) {
      if (id) {
        this.uploadParams.id = id
        try {
          const res = await questionDetail({ id })
          this.uploadParams = res.data
        } catch (e) {
          console.log(e)
        }
      }
    },
    onProvinceChang () {
      this.uploadParams.city = null
    },
    onSubjectChange (sId) {
      this.catalogList = null
      this.uploadParams.catalogID = null
      this.getSimpleDirectorys(sId)
      this.uploadParams.tags = null
      this.getSimpleTag(sId)
    },
    onQuestionTypeChange () {
      this.uploadParams.options.forEach(item => {
        item.isRight = false
      })
      this.mySelect = false
    },
    addOption () {
      this.uploadParams.options.push(undefined)
    },
    submitData () {
      this.$refs.uploadParams.validate((valid) => {
        if (valid) {
          if (this.isEdit) {
            this.questionUpdate()
          } else {
            this.addQuestions()
          }
        } else {
          console.log('error submit!!')
          return false
        }
      })
    }
  },
  computed: {
    provinces () {
      return provinces()
    },
    citys () {
      if (this.uploadParams.province) {
        return citys(this.uploadParams.province)
      }
      return null
    },
    difficList () {
      return difficList
    },
    questionTypeList () {
      return questionList
    },
    showOptionView () {
      return this.uploadParams.questionType !== '3'
    },
    isSingleOption () {
      return this.uploadParams.questionType === '1'
    },
    tagData: {
      get () {
        // ：value
        if (this.uploadParams.tags) {
          return this.uploadParams.tags.split(',')
        }
        return this.uploadParams.tags
      },
      set (val) {
        this.uploadParams.tags = val.join(',')
      }
    },
    isEdit () {
      return this.uploadParams.id
    }
  },
  watch: {
    $route (to, from) {
      const id = to.query.id
      if (id) {
        this.getQuestionsInfo(to.query.id)
      } else {
        this.clearFrom()
      }
    }
  },
  created () {
    this.getSimpleSubjects()
    this.getCompanys()
    this.getQuestionsInfo(this.$route.query.id)
  }
}
</script>

<style scoped lang='less'>
.container {
  margin: 10px;

  /deep/ .rich-text {
    height: fit-content;

    .ql-container {
      min-height: 200px;
    }
  }
}
</style>
